package be.devijver.bejug.jetty;

import java.io.File;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Map.Entry;

import org.mortbay.http.SocketListener;
import org.mortbay.jetty.Server;
import org.springframework.beans.factory.config.AbstractFactoryBean;

public class JettyWebServerFactoryBean extends AbstractFactoryBean {

	@Override
	protected void destroyInstance(Object server) throws Exception {
		((Server)server).stop();
	}

	private int port = 8080;

	public void setPort(int port) {
		this.port = port;
	}

	private Properties webApplications;

	public void setWebApplications(Properties props) {
		this.webApplications = props;
	}

	private Server server;

	@Override
	protected Object createInstance() throws Exception {
		server = new Server();
		SocketListener socketListener = new SocketListener();
		socketListener.setPort(port);

		server.addListener(socketListener);

		if (webApplications != null) {
			for (Iterator iter = webApplications.entrySet().iterator(); iter.hasNext();) {
				Map.Entry entry = (Entry) iter.next();
				String context = (String) entry.getKey();
				String location = (String) entry.getValue();

				if (!context.startsWith("/")) {
					throw new IllegalArgumentException("Context name [" + context + "] does not start with /");
				}
				if (!new File(location).exists()) {
					throw new IllegalArgumentException("Web application location [" + location + "] for context [" + context + "] does not exist");
				}

				server.addWebApplication(context, location);
			}
		}

		server.start();

		return server;
	}

	public Class getObjectType() {
		return Server.class;
	}

}
